<template>
  <div class="school-info-edit">
    <h2 class="section-title">学校基本信息</h2>

    <el-form :model="schoolForm" :rules="schoolRules" ref="schoolFormRef" label-position="top">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="学校名称" prop="name">
            <el-input v-model="schoolForm.name" placeholder="请输入学校名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="学校地址" prop="address">
        <el-input v-model="schoolForm.address" placeholder="请输入学校地址"></el-input>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="成立日期" prop="establishedDate">
            <el-date-picker
              v-model="schoolForm.establishedDate"
              type="date"
              placeholder="选择成立日期"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="官方网站" prop="website">
            <el-input v-model="schoolForm.website" placeholder="请输入学校官网地址">
              <template #prepend>http://</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="schoolForm.contactPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input v-model="schoolForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="学校简介" prop="description">
        <el-input type="textarea" v-model="schoolForm.description" placeholder="请输入学校简介" :rows="4"></el-input>
      </el-form-item>

      <el-form-item label="学校校徽">
        <div class="logo-upload">
          <div class="preview-container">
            <img
              v-if="previewUrl"
              :src="previewUrl"
              alt="校徽预览"
              class="logo-preview"
            >
            <div v-else class="logo-placeholder">
              <i class="el-icon-picture-outline"></i>
              <span>校徽预览</span>
            </div>
          </div>

          <el-upload
            class="upload-container"
            action="#"
            :http-request="uploadLogo"
            :show-file-list="false"
            accept="image/jpeg,image/png,image/gif"
          >
            <el-button type="primary">{{ schoolForm.logo ? '更换校徽' : '上传校徽' }}</el-button>
            <div class="upload-tip">推荐上传正方形图片，最大支持2MB</div>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveSchoolInfo" :loading="saving">保存修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  schoolId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['updated'])

// 表单引用和状态
const schoolFormRef = ref(null)
const previewUrl = ref('')
const saving = ref(false)
const schoolForm = ref({
  name: '',
  address: '',
  description: '',
  establishedDate: null,
  website: '',
  contactPhone: '',
  contactEmail: '',
  logo: null,
  logoFile: null
})

// 表单验证规则
const schoolRules = {
  name: [
    { required: true, message: '请输入学校名称', trigger: 'blur' },
    { min: 2, max: 50, message: '学校名称长度应在2-50个字符之间', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入学校地址', trigger: 'blur' },
    { max: 200, message: '地址长度不能超过200个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '简介长度不能超过500个字符', trigger: 'blur' }
  ],
  website: [
    { type: 'url', message: '请输入有效的网址', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^[\d\-]+$/, message: '请输入有效的电话号码', trigger: 'blur' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

// 监听schoolId变化，重新加载数据
watch(() => props.schoolId, (newValue) => {
  if (newValue) {
    fetchSchoolData()
  }
})

// 获取学校信息
const fetchSchoolData = async () => {
  try {
    const response = await axios.get(`http://localhost:5000/school/${props.schoolId}`)
    const schoolData = response.data

    schoolForm.value.name = schoolData.name || ''
    schoolForm.value.address = schoolData.address || ''
    schoolForm.value.description = schoolData.description || ''
    schoolForm.value.establishedDate = schoolData.establishedDate || null
    schoolForm.value.website = schoolData.website || ''
    schoolForm.value.contactPhone = schoolData.contactPhone || ''
    schoolForm.value.contactEmail = schoolData.contactEmail || ''
    schoolForm.value.logo = schoolData.logo || null

    if (schoolData.logo) {
      previewUrl.value = `http://localhost:5000/uploads/${schoolData.logo}`
    } else {
      previewUrl.value = ''
    }
  } catch (error) {
    console.error('获取学校信息失败:', error)
    ElMessage.error('获取学校信息失败')
  }
}

// 处理校徽上传
const uploadLogo = async (options) => {
  const file = options.file

  // 检查文件大小 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过2MB')
    return
  }

  // 预览
  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target.result
  }
  reader.readAsDataURL(file)

  // 存储文件以便后续上传
  schoolForm.value.logoFile = file
}

// 保存学校信息
const saveSchoolInfo = async () => {
  schoolFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }

    saving.value = true
    try {
      const token = localStorage.getItem('token')

      // 准备FormData用于文件上传
      const formData = new FormData()
      formData.append('name', schoolForm.value.name)
      formData.append('address', schoolForm.value.address)
      formData.append('description', schoolForm.value.description)
      formData.append('establishedDate', schoolForm.value.establishedDate ? new Date(schoolForm.value.establishedDate).toISOString() : '')
      formData.append('website', schoolForm.value.website)
      formData.append('contactPhone', schoolForm.value.contactPhone)
      formData.append('contactEmail', schoolForm.value.contactEmail)

      // 如果有新的校徽文件，则添加到表单数据
      if (schoolForm.value.logoFile) {
        formData.append('logo', schoolForm.value.logoFile)
      }

      // 发送更新请求
      const response = await axios.put(
        `http://localhost:5000/school/${props.schoolId}`,
        formData,
        {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'multipart/form-data'
          }
        }
      )

      if (response.status === 200) {
        ElMessage.success('学校信息更新成功')
        emit('updated')
        location.reload()
      } else {
        ElMessage.error('更新失败: ' + (response.data.message || '未知错误'))
      }
    } catch (error) {
      console.error('更新学校信息失败:', error)
      ElMessage.error('更新学校信息失败，请稍后重试')
    } finally {
      saving.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  schoolFormRef.value.resetFields()
  fetchSchoolData()
}

// 组件挂载时获取学校数据
onMounted(() => {
  if (props.schoolId) {
    fetchSchoolData()
  }
})
</script>

<style scoped>
.school-info-edit {
  padding: 20px 0;
}

.section-title {
  color: #fff;
  font-size: 24px;
  margin-bottom: 30px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-form-item__label) {
  color: #b0bec5;
  font-size: 16px;
}

:deep(.el-input__inner), :deep(.el-textarea__inner), :deep(.el-input-group__prepend), :deep(.el-select .el-input__inner), :deep(.el-date-editor .el-input__inner) {
  background-color: #1f1b24 !important;
  border-color: #444 !important;
  color: #fff !important;
}

:deep(.el-input__inner:focus), :deep(.el-textarea__inner:focus), :deep(.el-select .el-input.is-focus .el-input__inner), :deep(.el-date-editor.is-active .el-input__inner) {
  border-color: #00aeff !important;
}

:deep(.el-input-group__prepend) {
  background-color: #28232e !important;
  border-color: #444 !important;
  color: #b0bec5 !important;
  border-right: none;
}

.logo-upload {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.preview-container {
  width: 150px;
  height: 150px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #1f1b24;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #555;
}

.logo-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
}

.logo-placeholder i {
  font-size: 40px;
  margin-bottom: 10px;
}

.upload-container {
  flex: 1;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

:deep(.el-button) {
  min-width: 100px;
}

:deep(.el-select-dropdown), :deep(.el-picker-panel) {
  background-color: #1f1b24 !important;
  border-color: #444 !important;
}

:deep(.el-select-dropdown__item), :deep(.el-date-table td) {
  color: #b0bec5 !important;
}

:deep(.el-select-dropdown__item.hover), :deep(.el-select-dropdown__item:hover), :deep(.el-date-table td.available:hover) {
  background-color: #28232e !important;
}

:deep(.el-date-table td.current:not(.disabled)) span {
  background-color: #00aeff !important;
}

:deep(.el-picker-panel__icon-btn), :deep(.el-picker-panel__header-label) {
  color: #b0bec5 !important;
}
</style>
